/* main.c -- MQTT client example
*
* Copyright (c) 2014-2015, Tuan PM <tuanpm at live dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/

#include "ets_sys.h"
#include "driver/uart.h"
#include "osapi.h"
#include "mqtt.h"
#include "config.h"
#include "debug.h"
#include "gpio.h"
#include "user_interface.h"
#include "mem.h"
#include "user_config.h"
#include "smartconfig.h"
#include "airkiss.h"
#include "httpclient.h"

void wifi_handle_event_cb(System_Event_t *evt)
{
 switch (evt->event) {
	case EVENT_STAMODE_GOT_IP:
	#if	defined(_COMM_PRO_SEL_MQTT)
		mqtt_connect_to_server();
	#elif defined(_COMM_PRO_SEL_HTTP)
		module_net_state = 1;
	#endif
	#if	defined(_DEVICE_FIND)
		user_devicefind_init();
		user_tcpserver_init(SERVER_LOCAL_PORT);
	#endif
		INFO("------EVENT_STAMODE_GOT_IP got ip:" IPSTR ",mask:" IPSTR ",gw:" IPSTR,
		IP2STR(&evt->event_info.got_ip.ip),
		IP2STR(&evt->event_info.got_ip.mask),
		IP2STR(&evt->event_info.got_ip.gw));
		INFO("\n");
	break;
	case EVENT_STAMODE_CONNECTED:
		INFO("-------connect to ssid %s, channel %d\n",
		evt->event_info.connected.ssid,
		evt->event_info.connected.channel);
	break;
	case EVENT_STAMODE_DISCONNECTED:
		mqtt_disconnect_from_server();
		INFO("--------disconnect from ssid %s, reason %d\n",
		evt->event_info.disconnected.ssid,
		evt->event_info.disconnected.reason);
	break;
	case EVENT_STAMODE_AUTHMODE_CHANGE:
		INFO("-------mode: %d -> %d\n",evt->event_info.auth_change.old_mode,evt->event_info.auth_change.new_mode);
	break;

	case EVENT_SOFTAPMODE_STACONNECTED:
		INFO("-------station: " MACSTR "join, AID = %d\n",MAC2STR(evt->event_info.sta_connected.mac),evt->event_info.sta_connected.aid);
	break;
	case EVENT_SOFTAPMODE_STADISCONNECTED:
	#if	defined(_COMM_PRO_SEL_MQTT)
		mqtt_disconnect_from_server();
	#elif defined(_COMM_PRO_SEL_HTTP)
		module_net_state = 0;
	#endif
		INFO("--------station: " MACSTR "leave, AID = %d\n",MAC2STR(evt->event_info.sta_disconnected.mac),evt->event_info.sta_disconnected.aid);
	break;
	default: break;
 }
}
/******************************************************************************
 * FunctionName : user_rf_cal_sector_set
 * Description  : SDK just reversed 4 sectors, used for rf init data and paramters.
 *                We add this function to force users to set rf cal sector, since
 *                we don't know which sector is free in user's application.
 *                sector map for last several sectors : ABCCC
 *                A : rf cal
 *                B : rf init data
 *                C : sdk parameters
 * Parameters   : none
 * Returns      : rf cal sector
 *******************************************************************************/
uint32 ICACHE_FLASH_ATTR
user_rf_cal_sector_set(void)
{
    enum flash_size_map size_map = system_get_flash_size_map();
    uint32 rf_cal_sec = 0;

    switch (size_map) {
        case FLASH_SIZE_4M_MAP_256_256:
            rf_cal_sec = 128 - 5;
            break;

        case FLASH_SIZE_8M_MAP_512_512:
            rf_cal_sec = 256 - 5;
            break;

        case FLASH_SIZE_16M_MAP_512_512:
        case FLASH_SIZE_16M_MAP_1024_1024:
            rf_cal_sec = 512 - 5;
            break;

        case FLASH_SIZE_32M_MAP_512_512:
        case FLASH_SIZE_32M_MAP_1024_1024:
            rf_cal_sec = 1024 - 5;
            break;

        case FLASH_SIZE_64M_MAP_1024_1024:
            rf_cal_sec = 2048 - 5;
            break;
        case FLASH_SIZE_128M_MAP_1024_1024:
            rf_cal_sec = 4096 - 5;
            break;
        default:
            rf_cal_sec = 0;
            break;
    }

    return rf_cal_sec;
}



void user_init(void)
{
	#if defined(_DEBUG_USER)
		system_set_os_print(1);
	#endif
    uart_init(BIT_RATE_115200, BIT_RATE_115200);
	#if defined(_SERIAL_SEL)
    	system_uart_swap();    //use this one to output debug information via uart1 //
	#endif
	#if defined(_HARDWARE_OP)
    	user_timer_wifistate_init();
        WIFI_STATE_PIN_WR_INIT();
    	drv_Switch_Init();
	#endif

	if(wifi_get_macaddr(STATION_IF, sta_mac)==true)
	{
		os_memset(mqtt_mac,0x00,sizeof(mqtt_mac));
		os_sprintf(mqtt_mac, MACSTR, MAC2STR(sta_mac));
		os_printf("--------------mqtt_mac:%s",mqtt_mac);
	}

	smartconfig_set_type(SC_TYPE_ESPTOUCH_AIRKISS);

	wifi_set_event_handler_cb(wifi_handle_event_cb);

	#if	defined(_COMM_PRO_SEL_MQTT)
		mqtt_init();
	#endif

	user_timer_heartbeat_init();

	if (system_upgrade_userbin_check() == UPGRADE_FW_BIN1) {
		os_printf("-----user1.bin\n");
	} else if (system_upgrade_userbin_check() == UPGRADE_FW_BIN2) {
		os_printf("-----user2.bin\n");
	}
    INFO("\r\nSystem started ...\r\n");
}
